package com.longe.netty.transferFiles.client;

import com.longe.netty.transferFiles.domain.FileTransferProtocol;
import com.longe.netty.transferFiles.util.MsgUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;

public class NettyClient {

    public static void main(String[] args) {
        //启动客户端
        System.err.println("netty client start done.");
        new NettyClient().connect("127.0.0.1", 7397);
    }


    public void connect(String host, int port) {
        //配置服务端NIO线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new MyChannelInitializer());
            ChannelFuture channelFuture = b.connect(host, port).syncUninterruptibly();

            //文件信息{文件大于1kb方便测试断点续传}
            File file = new File("D:\\test\\aaa\\测试传输文件.rar");
            FileTransferProtocol fileTransferProtocol = MsgUtil
                    .buildRequestTransferFile(file.getAbsolutePath(), file.getName(), file.length());
            //发送信息；请求传输文件
            Channel channel = channelFuture.channel();
            channel.writeAndFlush(fileTransferProtocol);

            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}